package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Banner;
import com.itheima.domain.BannerExample;
import com.itheima.mapper.BannerMapper;
import com.itheima.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional/*开启事务*/
public class BannerServiceImpl implements BannerService {
    @Autowired
    private BannerMapper bannerMapper;
    /*分页查询轮播图*/
    @Override
    public PageInfo<Banner> findByPage(Integer pageNum, Integer pageSize) {
        /*开启分页拦截*/
        PageHelper.startPage(pageNum, pageSize);
        BannerExample bannerExample = new BannerExample();
        List<Banner> banners = bannerMapper.selectByExample(bannerExample);
        return new PageInfo<>(banners);
    }

    /**
     * 根据关键字查询
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageInfo<Banner> findByPage(Integer pageNum, Integer pageSize, String keyword) {
        /*开启分页拦截*/
        PageHelper.startPage(pageNum, pageSize);
        BannerExample bannerExample = new BannerExample();
        if (keyword != null && !keyword.equals("")) {
            bannerExample.createCriteria().andTitleLike("%" + keyword + "%");
        }
        List<Banner> banners = bannerMapper.selectByExample(bannerExample);
        //封装在pageInfor中
        return new PageInfo<>(banners);
    }

    /*添加 或修改，判断是否有id*/
    @Override
    public void save(Banner banner) {
        //判断是否有id，没有就是添加
        if (banner.getId() == null) {
            bannerMapper.insertSelective(banner);
        }
        else {
            //修改
            bannerMapper.updateByPrimaryKeySelective(banner);
        }



    }

    //根据id查询
    @Override
    public Banner findById(Integer id) {
        Banner banner = bannerMapper.selectByPrimaryKey(id);
        return banner;

    }



    //根据id删除
    @Override
    public void deleteById(Integer id) {
        bannerMapper.deleteByPrimaryKey(id);

    }

    //根据id数组进行删除
    @Override
    public void deleteByIds(Integer[] ids) {
        for (Integer id : ids) {
            bannerMapper.deleteByPrimaryKey(id);

        }

    }


}
